package com.bawei.livedata.net;

import com.bawei.livedata.entity.BaseResponseEntity;

import java.lang.reflect.Type;

import androidx.lifecycle.LiveData;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @Author : yaotianxue
 * @Time : On 2023/9/15 08:04
 * @Description : LiveDataCallAdapter
 */
public class LiveDataCallAdapter<R> implements CallAdapter<R, LiveData<R>> {
    private Type mType;//返回类型 BaseResponseEntity

    public LiveDataCallAdapter(Type type) {
        mType = type;
    }

    @Override
    public Type responseType() {
        return mType;
    }

    @Override
    public LiveData<R> adapt(Call<R> call) {
        return new LiveData<R>() {
            @Override
            protected void onActive() {
                super.onActive();
                call.enqueue(new Callback<R>() {
                    @Override
                    public void onResponse(Call<R> call, Response<R> response) {//请求到数据
                        if(response.code() == 200){//成功
                            postValue(response.body());
                        }else{//失败
                            BaseResponseEntity baseResponseEntity = new BaseResponseEntity(505,response.message());
                            postValue((R)baseResponseEntity);
                        }

                    }

                    @Override
                    public void onFailure(Call<R> call, Throwable t) {//请求数据失败
                        BaseResponseEntity baseResponseEntity = new BaseResponseEntity(505,t.getMessage());
                        postValue((R)baseResponseEntity);

                    }
                });

            }
        };
    }


}
